//引入VueRouter
import VueRouter from 'vue-router'
//引入Vue
import Vue from 'vue'

import store from '@/store'

//使用路由
Vue.use(VueRouter)

//创建router实例对象，去管理一组一组的路由规则
const router = new VueRouter({
	mode: 'hash',
	routes: [
		{
			path: '/Home',
			component: () => import("@/pages/Home"),
			meta: { FooterShow: true }   //决定Footer组件是否显示与隐藏
		},
		{
			path: '/Login',
			component: () => import("@/pages/Login"),
			meta: { FooterShow: true }
		}, {
			path: '/Register',
			component: () => import("@/pages/Register"),
			meta: { FooterShow: true }
		},
		{
			// path:'/Search/keyword?',会导致路由无法正常跳转。
			path: '/Search/:keyword?',
			component: () => import("@/pages/Search"),
			name: "Search",
			meta: { FooterShow: true }
		},
		{
			path: '/Detail/:skuId?',
			component: () => import("@/pages/Detail"),
			name: "Detail",
			meta: { FooterShow: true }
		},
		{
			path: '/ShopCart',
			component: () => import("@/pages/ShopCart"),
			name: "ShopCart",
			meta: { FooterShow: true }
		},
		{
			path: '/AddCartSuccess',
			component: () => import("@/pages/AddCartSuccess"),
			name: "AddCartSuccess",
			meta: { FooterShow: false }
		},
		{
			path: '/Trade',
			component: () => import("@/pages/Trade"),
			name: "Trade",
			meta: { FooterShow: false }
		},
		{
			path: '/Pay',
			component: () => import("@/pages/Pay"),
			name: "Pay",
			meta: { FooterShow: false }
		},
		//重定向，在项目跑起来的时候，访问/，立马让他定向到首页
		{
			path: '*',
			redirect: '/Home',
			meta: { FooterShow: true }
		}
	],
	//滚动行为：跳转路由时让滚轮回到顶部
	scrollBehavior(to, from, savedPPosition) {
		return { y: 0 }
	}
})
router.beforeEach(async (to, from, next) => {
	// next();
	let token = store.state.user.token
	let userInfo = store.state.user.userInfo
	// let name = store.state.user.userInfo.name
	if (token) {
		//已登录，不允许用户去到Login路由
		if (to.path == '/Login') {
			next('/Home')
		} else {
			next();//不去Login，放行
		}
	} else {//没登录
		//判断是否有userInfo，有则放行，没有则重新派发下getUserInfo
		if (userInfo) {	// if (name)
			next();
		} else {
			try {
				next()
			} catch (error) {
				//console.log(''没调用过)
				await store.dispatch('getLoginOut')
				next('/Login')
			}
		}
		// next()
	}

})

//将创建的路由交由此处，暴露router
export default router